﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DBService;
using DBService.ViewDatas;

public partial class UserProfile : System.Web.UI.Page, ICallbackEventHandler
{
    int ProfileID;
    int PageSize = 10;
    int ItemCount;
    int PagesCount;
    string callBackData = String.Empty;
    int? userId = null;
    int? subScriberID = null;
    string deleteReviewAdmin = "<a name=\"DeleteReviewAdmin\" class=\"red_x\" href=\"#\"></a>";
    ModelAdapter service = null;

    protected void Page_Load(object sender, EventArgs e)
    {
        service = new ModelAdapter();
        userId = Session["UserID"] == null ? null : (int?)int.Parse(Session["UserID"].ToString());
        if (int.TryParse((string)Request.QueryString["id"], out ProfileID))
        {
            var UserObj = Master.GetAuthedUserObject();
            if (userId != null || UserObj == null || UserObj.UserType != 0)
            {
                deleteReviewAdmin = "";
            }

            InitPage();

            #region callback scripts
            ClientScriptManager cm = Page.ClientScript;
            String cbReference = cm.GetCallbackEventReference(this, "arg", "ReceiveServerData", "");
            String callbackScript = "function CallServer(arg, context) {" + cbReference + "; }";
            cm.RegisterClientScriptBlock(this.GetType(), "CallServer", callbackScript, true);
            #endregion
        }
        else
        {
            Response.Redirect("userratings.aspx");
        }
        SubScriberMethode();
    }

    private void SubScriberMethode()
    {
        if (userId == ProfileID)
        {
            ProfileEdit.Visible = true;
            SubscriberID.Visible = false;
            UnSubscriberID.Visible = false;
        }
        else if (userId != null && !service.IsUserSubScribed(userId.Value, ProfileID))
        {
            SubscriberID.Visible = true;
            UnSubscriberID.Visible = false;
        }
        else if (userId != null)
        {
            UnSubscriberID.Visible = true;
            SubscriberID.Visible = false;
        }
    }

    public void InitPage()
    {
        ModelAdapter adapter = new ModelAdapter();
        UserInfo userInfo = adapter.GetUser(ProfileID);
        firstName.InnerText = userInfo.FirstName;
        lastName.InnerText = userInfo.LastName;
        gender.InnerText = userInfo.gender == true ? "მამრობითი" : userInfo.gender == false ? "მდედრობითი" : "არ არის მითითებული.";
        birthdate.InnerText = userInfo.bithDate.ToShortDateString();
        birthdate.InnerText += " " +
            ((DateTime.Now.Year - userInfo.bithDate.Year)
            + ((DateTime.Now.Month < userInfo.bithDate.Month ||
            (DateTime.Now.Month == userInfo.bithDate.Month && DateTime.Now.Day <= userInfo.bithDate.Day)) ? 0 : 1)) + " წლის";
        email.InnerText = "";// userInfo.mail;
        lastreview.InnerText = userInfo.LastReviewDate.ToString();
        rateing.InnerHtml = "<span> რეიტინგი" + "&rarr;" + userInfo.Rateing + "</span>";
        rateing.Style.Add(HtmlTextWriterStyle.Width, (userInfo.Rateing * 20).ToString() + "%");
        Signature.InnerText = userInfo.Signature ?? "სტატუსი ცარიელია";
        UserReviewsCount.Text = userInfo.ReviewCount.HasValue ? userInfo.ReviewCount.ToString() : "0";

        ActiveCategory.InnerText = adapter.GetUserMostActiveCategory(ProfileID);
        if (userInfo.UserFB.HasValue)
        {
            UserAvatarImg.Src = String.Format("http://graph.facebook.com/{0}/picture?width=50&height=50", userInfo.UserFB.ToString());
        }
        else
        {
            UserAvatarImg.Src = String.IsNullOrEmpty(userInfo.Avatar) ? UserAvatarImg.Src : "upload/" + userInfo.Avatar;
        }
        if (userId != ProfileID)
        {
            EditUser.HRef = "#";
            editSignature.Visible = false;
        }
        else if (userId == ProfileID)
        {
            EditUser.HRef = "edituserprofile.aspx?id=" + ProfileID;
        }
        BindRepeater();
    }

    public void ReviewHistoryRep_DataBound(Object Sender, RepeaterItemEventArgs e)
     {
        var item = (UserProfileReviewInfo)e.Item.DataItem;
        if (item != null)
        {
            var lit = (Literal)e.Item.FindControl("ReviewItem");

            string minutesAgo = "";
            var crdate = (item.CreateDate ?? DateTime.Now.AddDays(-20));
            var subs = (DateTime.Now - crdate);
            minutesAgo = subs.TotalMinutes < 60 ? subs.Minutes + " წუთის წინ..." : crdate.ToShortDateString();

            string reviewImages = "";
            if (item.ReviewGalleryObj != null && item.ReviewGalleryObj.GalleryFiles != null && item.ReviewGalleryObj.GalleryFiles.Count > 0)
            {
                int iCountImgs = 1;
                reviewImages += "<div class=\"rev_imgs\">";
                foreach (var file in item.ReviewGalleryObj.GalleryFiles)
                {
                    if (iCountImgs > 2)
                    {
                        reviewImages += "<a rel=\"usercompanyimages\"  href=\"upload/" + file.File.FilePath + "\" ><img style=\"display:none;\" width=\"172\" height=\"92\" src=\"upload/" + file.File.FilePath + "\"></a>";
                    }
                    else
                    {
                        reviewImages += "<a rel=\"usercompanyimages\"  href=\"upload/" + file.File.FilePath + "\" ><img width=\"172\" height=\"92\" src=\"upload/" + file.File.FilePath + "\"></a>";
                    }
                    iCountImgs++;
                }
                reviewImages += "</div>";
            }

            if (item.Reviews != null)
            {
                string avat = UserAvatarImg.Src;

                lit.Text = "<div class=\"rev_block\">" +
                               "<div class=\"img_mind\"><img src=\"" + avat + "\" width=\"50\" height=\"50\" /></div>" +
                               "<div class=\"user_review\">" +
                                    "<div class=\"u_name\">" + item.FirstName +
                                        "<img src=\"images/arow.png\" width=\"12\" height=\"9\" />" +
                                        "<a href=\"SingleCompany.aspx?id=" + item.CompanyID + "\">" + item.CompanyName + "</a>" +
                                    "</div>" +
                               "<div class=\"rev_txt\">" + item.Reviews + "</div>" +
                               "<div class=\"rev_time\" revid=\"" + item.ReviewID + "\">"
                                                    + minutesAgo
                                                    + deleteReviewAdmin +
                               "</div>" + reviewImages + "</div>" +
                               "<div class=\"clear\"></div>" +
                           "</div>";
            }
        }

    }

    private void BindRepeater()
    {
        var service = new ModelAdapter();
        var coll = service.GetUserProfileReviewInfos(ProfileID).OrderByDescending(p => p.CreateDate).ToList();
        ItemCount = coll.Count;

        PagedDataSource Pds1 = new PagedDataSource();
        Pds1.DataSource = coll;
        Pds1.AllowPaging = true;
        Pds1.PageSize = PageSize;
        ReviewHistoryRep.DataSource = Pds1;



        var lastIndex = PagesCount = ItemCount % PageSize == 0 ? (ItemCount / PageSize) : (ItemCount / PageSize) + 1;
        var startIndex = 1;

        if (lastIndex - startIndex > 0)
        {
            Pds1.CurrentPageIndex = CurrentPage;
            pages.Controls.Clear();
            for (int i = startIndex; i <= lastIndex; i++)
            {
                var lb = new LinkButton() { Text = i.ToString(), CssClass = "page_bg_num" };
                lb.ID = "btnlink" + i.ToString();
                lb.CssClass = "page_bg_num";
                lb.Click += new EventHandler(lb_Click);
                pages.Controls.Add(lb);
            }
            if (CurrentPage != lastIndex - 1)
            {
                // show next
                var lb1 = new LinkButton() { Text = "►", CssClass = "page_bg_num" };
                lb1.ID = "btnlink-1";
                lb1.Click += new EventHandler(lb_Click);
                pages.Controls.Add(lb1);

                // show last
                var lblast = new LinkButton() { Text = "ბოლო", CssClass = "page_bg_num" };
                lblast.ID = "lblast100";
                lblast.CssClass = "page_last";
                lblast.Click += new EventHandler(lb_Click);
                pages.Controls.Add(lblast);
            }
        }
        ReviewHistoryRep.DataBind();
    }

    protected void SubsciberClick(object sender, EventArgs e)
    {
        service.AddSubSciberUser(userId.Value, ProfileID);
        SubScriberMethode();
    }

    protected void UnSubsciberClick(object sender, EventArgs e)
    {
        service.UnSubScribeUser(userId.Value, ProfileID);
        SubScriberMethode();
    }

    protected void lb_Click(object sender, EventArgs e)
    {
        var lb = (LinkButton)sender;
        if (lb.Text == "ბოლო")
        {
            CurrentPage = 10000;
        }
        else if (lb.Text == "►")
        {
            CurrentPage += 1;
        }
        else
        {
            CurrentPage = int.Parse(lb.Text) - 1;
        }
        BindRepeater();
    }

    public int CurrentPage
    {
        get
        {
            object s1 = this.ViewState["CurrentPage"];
            if (s1 == null)
            {
                return 0;
            }
            else
            {
                return Convert.ToInt32(s1);
            }
        }
        set
        {
            if (value > PagesCount - 1)
            {
                value = PagesCount - 1;
            }
            this.ViewState["CurrentPage"] = value;
        }
    }

    string ICallbackEventHandler.GetCallbackResult()
    {
        return callBackData;
    }

    void ICallbackEventHandler.RaiseCallbackEvent(string eventArgument)
    {
        try
        {
            var ma = new ModelAdapter();
            var parts = eventArgument.Split('|');
            if (String.IsNullOrEmpty(eventArgument))
            {
                callBackData = "Error|დაფიქსირდა შეცდომა";
                return;
            }
            callBackData = "Success|";


            switch (parts[0])
            {
                case "RemoveReview":
                    {
                        var RevID = int.Parse(parts[1]);
                        callBackData += "RemoveReview|" + ma.ReviewDelete(RevID);
                        break;
                    }
                case "EditSignature":
                    {
                        if (Session["UserID"] == null)
                        {
                            return;
                        }
                        QuickEditor editor = new QuickEditor();
                        var user = editor.objectContext.Users.Where(u => u.UserID == ProfileID).SingleOrDefault();
                        if (user != null)
                        {
                            user.Signature = parts[1];
                            editor.objectContext.SaveChanges();
                        }
                        break;
                    }
                default:
                    {
                        break;
                    }
            }
        }
        catch (Exception ex)
        {
            callBackData = "Error|დაფიქსირდა შეცდომა";
            return;
        }
    }

}
